package com.msmall.community.bbs.service.impl;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.msmall.base.cache.CacheFactory;
import com.msmall.base.pager.MatchType;
import com.msmall.base.pager.PaginationSupport;
import com.msmall.base.service.impl.BaseManagerImpl;
import com.msmall.base.util.ConstantDB;
import com.msmall.base.util.Constants;
import com.msmall.community.bbs.dao.BoardDao;
import com.msmall.community.bbs.model.Board;
import com.msmall.community.bbs.model.BoardKeyword;
import com.msmall.community.bbs.model.Topic;
import com.msmall.community.bbs.service.BoardManager;
import com.msmall.community.bbs.service.MasterManager;
import com.msmall.community.common.CascadeCollection;

public class BoardManagerImpl extends BaseManagerImpl<Board, Long> implements BoardManager{

	private static final Log logger = LogFactory.getLog(BoardManagerImpl.class);
	
	private BoardDao boardDao;
	
	private MasterManager masterManager;
	
	public void setMasterManager(MasterManager masterManager) {
		this.masterManager = masterManager;
	}
	public void setBoardDao(BoardDao boardDao) {
		this.boardDao = boardDao;
	}
	
	/**
	 * 通过boardid获得此版权下的所有关键字，orders 1,2,3
	 */
	public List<BoardKeyword> getKeywordsByBoardid(Long boardid){
		try {
			return boardDao.getKeywordsByBoardid(boardid);
		} catch (Exception e) {
			logger.debug(e);
		}
		return null;
	}
	public Board getBoard(Long boardId){
		Iterator it = getAllBoard().iterator();
		Board board = null;
		while(it.hasNext()){
			board = (Board)it.next();
			if(boardId.compareTo(board.getBoardId()) == 0){
				break;
			}
		}
		return board;
	}
	public void saveBoard(Board board) {
		Long origianlId = board.getBoardId();
		Long newParentId = board.getParentId();
		if(origianlId == null){ //如果是创建 则为null
			boardDao.save(board);
			List boards = boardDao.getByProperty(Board.class, "chineseName", MatchType.EQ, board.getChineseName());
			board = (Board) boards.get(0);
			masterManager.saveBoardMaster(board.getBoardId());
		}else{ //如果是修改，ID不变，判断父版区是否修改，如果修改，更新版主关系
			Board old = (Board) boardDao.get(Board.class, origianlId);
			boardDao.save(board);
			if(old.getParentId().compareTo(newParentId) != 0){
				masterManager.saveBoardMaster(board.getBoardId());
			}
		}
	}

	public List<Board> getAllBoard() {
		List<Board> list = new ArrayList<Board>();
		CascadeCollection<Board> cs = (CascadeCollection<Board>) CacheFactory.getInstance().getCache(Constants.CACHE_NAME_COMMON).get(Constants.CACHE_KEY_BBS_BOARD_CASCADECOLLECTION);
		for(CascadeCollection<Board> c : cs.getAllDatas().values()){
			list.add(c.getCurrent());
		}
		return list;
	}
	
	public List<Board> getAllAvailableBoard(){
		List<Board> boards = getAllBoard();
		for(int i = 0; i < boards.size(); i ++){
			Board board = boards.get(i);
			if(board.getEnabled().compareTo((short)0) == 0){
				boards.remove(i);
			}
		}
		return boards;
	}
	
	public List<Board> getChildBoard(Long boardId) {
		List<Board> boards = new ArrayList<Board>();
		Iterator it = getAllBoard().iterator();
		while(it.hasNext()){
			Board board = (Board) it.next();
			if(boardId.compareTo(board.getParentId()) ==0){
				boards.add(board);
			}
		}
		return boards;
	}
	public void getTopicPaginationByBoard(PaginationSupport pagination, Long userid, Long boardId, Long keywordid) {
		pagination.setClazz(Topic.class);
		
		StringBuilder builder = new StringBuilder();
		builder.append("from Topic t where t.enabled =").append(ConstantDB.AVALIABLE).append(" and t.boardid = ").append(boardId);
		if(keywordid != null && keywordid >0){
			builder.append(" AND t.keywordid=").append(keywordid);
		}
		builder.append(" ORDER BY t.createTime DESC");
//		String queryString = "from Topic t where t.enabled = 1 and t.boardid = " + boardId;
//		if(keywordid != null && keywordid >0){
//			queryString += " t.keywordid="+ keywordid;
//		}
//		queryString += " order by top desc, commend desc, elite desc, createTime desc";
		pagination.setQueryString(builder.toString());
		boardDao.getPagination(pagination);
	}
	/**
	 * 刷新所有数据到缓存
	 */
	public void refresh()throws Exception{
		try{
			List<Board> allDatas = boardDao.getAll(Board.class);
			if(allDatas == null || allDatas.size() == 0)
				return;
			for(Board board:allDatas){
				board.setKeywords(getKeywordsByBoardid(board.getBoardId()));
			}
			CascadeCollection<Board> cs = new CascadeCollection<Board>();
			cs.parser(allDatas, "boardId", "parentId", "orders", CascadeCollection.ORDERS_ASC);
			CacheFactory.getInstance().getCache(Constants.CACHE_NAME_COMMON).put(Constants.CACHE_KEY_BBS_BOARD_CASCADECOLLECTION, cs);
		}catch(Exception e){
			log.debug(e);
			throw e;
		}
	}
}
